package jnpf.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

@Component
public class ServerUrlUtil implements ApplicationListener<WebServerInitializedEvent> {

    private int serverPort;

    @Autowired(required = false)
    private HttpServletRequest request;

    @Override
    public void onApplicationEvent(WebServerInitializedEvent event) {
        this.serverPort = event.getWebServer().getPort();
    }

    /**
     * 获取服务器IP地址
     * @return IP地址
     */
    public String getServerIp() {
        try {
            return InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            // 如果无法获取本地IP，则尝试从请求中获取
            if (request != null) {
                String xffHeader = request.getHeader("X-Forwarded-For");
                if (xffHeader == null) {
                    return request.getRemoteAddr();
                }
                return xffHeader.split(",")[0];
            }
            return "127.0.0.1";
        }
    }

    /**
     * 获取服务器端口
     * @return 端口号
     */
    public int getServerPort() {
        return serverPort;
    }

    /**
     * 获取服务器基础URL路径（如：http://192.168.1.100:8080）
     * @return 基础URL路径
     */
    public String getBaseUrl() {
//        return String.format("http://%s:%d", getServerIp(), getServerPort());
        return String.valueOf(getServerPort());
    }

    /**
     * 获取带上下文路径的完整基础URL（如：http://192.168.1.100:8080/context-path）
     * @return 完整基础URL
     */
    public String getFullBaseUrl() {
        if (request == null) {
            return getBaseUrl();
        }
        String contextPath = request.getContextPath();
        return contextPath.isEmpty() ? getBaseUrl() : getBaseUrl() + contextPath;
    }
}
